package com.ge.modules.api.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ge.common.exception.RRException;
import com.ge.common.validator.Assert;
import com.ge.modules.api.service.TbUserService;
import com.ge.modules.dao.TbUserCardDao;
import com.ge.modules.dao.TbUserDao;
import com.ge.modules.entity.TbUser;
import com.ge.modules.entity.TbUserCardEntity;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by wuye on 2017/11/24.
 */
@Service
@Transactional
public class TbUserServiceImpl extends ServiceImpl<TbUserDao, TbUser> implements TbUserService {

    @Autowired
    private TbUserDao userDao;

    @Autowired
    private TbUserCardDao tbUserCardDao;

    @Override
    public TbUser queryByMobile(String mobile) {
        return userDao.queryByMobile(mobile);
    }

    @Override
    public List<TbUser> queryList(Map<String, Object> map) {
        return userDao.queryList(map);
    }

    @Override
    @Transactional(rollbackFor=Exception.class)
    public void update(TbUser tbuser) {
        userDao.update(tbuser);
    }

    @Override
    public void updatePsByUserId(TbUser tbyser) {
        userDao.update(tbyser);
    }

    @Override
    public Page<TbUser> queryPageList(Page<TbUser> page, Map<String, Object> map) {
        page.setRecords(userDao.queryPageList(page, map));
        return page;
    }
    @Override
    public TbUser queryById(Integer id) {
        return userDao.selectByPrimaryKey(id);
    }

    @Override
    public TbUser foundById(Integer userId) {
        return userDao.selectByPrimaryKey(userId);
    }

    @Override
    public Integer login(String mobile, String password) {
        TbUser user = queryByMobile(mobile);
        Assert.isNull(user, "手机号或密码错误");
        //密码错误
        if (!user.getPassword().equals(DigestUtils.sha256Hex(password))) {
            throw new RRException("手机号或密码错误");
        }

        return user.getUserId();
    }

    @Override
    public void save(TbUser tbUser) {
        userDao.save(tbUser);
    }

    @Override
    public void saveUserAndCard(TbUser tbUser) {
        save(tbUser);
        //创建用户时初始化用户会员卡信息
        TbUserCardEntity tbUserCardEntity = new TbUserCardEntity();
        tbUserCardEntity.setBalance(BigDecimal.valueOf(0));
        tbUserCardEntity.setCreateTime(new Date());
        tbUserCardEntity.setUserId(tbUser.getUserId());
        tbUserCardEntity.setCardType(0);
        tbUserCardDao.save(tbUserCardEntity);
    }

}
